//
//  ToolDetailViewController.m
//  EasyBlueTooth
//
//  Created by nf on 2017/8/18.
//  Copyright © 2017年 chenSir. All rights reserved.
//

#import "ToolDetailViewController.h"
#import "ToolDetailCell.h"
#import "ToolDetailHeaderCell.h"
#import "ToolDetailHeaderView.h"

#import "EasyService.h"
#import "EasyUtils.h"
#import "EasyDescriptor.h"
#import "EFShowView.h"
#import "AppDelegate.h"
#import "ToolDetailOperationViewController.h"
#import "ALCommon.h"

typedef enum {
    SHOW_TYPE_NOTIY =1,
    SHOW_TYPE_WRITE,
}SHOW_TYPE;


@interface ToolDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)UITableView *tableView ;
@property (nonatomic,strong)NSArray *advertisementArray ;

@property (nonatomic,assign)__block BOOL isShowfirstSection ;//第一行是否打开

@property (nonatomic,assign)BOOL exitBreakUp ;//

@property (nonatomic,assign)SHOW_TYPE TYPE;

@end

@implementation ToolDetailViewController

- (void)dealloc
{
    //如果你想退出界面断开与设备的连接。就加上这句

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _TYPE = SHOW_TYPE_WRITE;
    
    self.advertisementArray = [self.peripheral.advertisementData allKeys];

    [self.view addSubview:self.tableView];
    [self loadRightSegmentedItem];
    

//    [EFShowView showHUDMsg:@"获取服务..." ];

//    kWeakSelf(self)

//    [self.peripheral discoverAllDeviceServiceWithCallback:^(EasyPeripheral *peripheral, NSArray<EasyService *> *serviceArray, NSError *error) {
//
////        NSLog(@"%@  == %@",serviceArray,error);
//
//        for (EasyService *tempS in serviceArray) {
////            NSLog(@" %@  = %@",tempS.UUID ,tempS.description);
//
//            [tempS discoverCharacteristicWithCallback:^(NSArray<EasyCharacteristic *> *characteristics, NSError *error) {
////                NSLog(@" %@  = %@",characteristics , error );
//
//                for (EasyCharacteristic *tempC in characteristics) {
//                    [tempC discoverDescriptorWithCallback:^(NSArray<EasyDescriptor *> *descriptorArray, NSError *error) {
////                        NSLog(@"%@ ====", descriptorArray)  ;
////                        if (descriptorArray.count > 0) {
////                            for (EasyDescriptor *d in descriptorArray) {
////                                NSLog(@"%@ - %@ %@ ", d,d.UUID ,d.value);
////                            }
////                        }
//                        for (EasyDescriptor *desc in descriptorArray) {
//                            [desc readValueWithCallback:^(EasyDescriptor *descriptor, NSError *error) {
////                                NSLog(@"读取descriptor的值：%@ ,%@ ",descriptor.value,error);
//                            }];
//                        }
//                        queueMainStart
//                        [EFShowView HideHud];
//                        [weakself.tableView reloadData ];
//                        queueEnd
//                    }];
//                }
//            }];
//        }
//    }];
    
//    [self performSelector:@selector(hideView) withObject:nil afterDelay:10];
}

- (void)loadRightSegmentedItem {
    NSArray *segmentedArray = [[NSArray alloc]initWithObjects:@"发送",@"接收",nil];
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedArray];
    segmentedControl.frame = CGRectMake(0, 0, 60, 30);
    segmentedControl.selectedSegmentIndex = 0;
    segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;
//    segmentedControl.momentary = YES;
    [segmentedControl addTarget:self action:@selector(didClicksegmentedControlAction:) forControlEvents:UIControlEventValueChanged];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
}

-(void)didClicksegmentedControlAction:(UISegmentedControl *)Seg{
    
    NSInteger Index = Seg.selectedSegmentIndex;
    
    switch (Index) {
            
        case 0:
            _TYPE = SHOW_TYPE_WRITE;
            break;
            
        case 1:
             _TYPE = SHOW_TYPE_NOTIY;
            break;

        default:
            
            break;
            
    }
     [self.tableView reloadData];
}

- (void)hideView {
    [EFShowView HideHud];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - tableView delegate 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.peripheral.serviceArray.count + 1 ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section) {
        EasyService *tempService = self.peripheral.serviceArray[section-1];
        return tempService.characteristicArray.count ;
    }
    
    if (_isShowfirstSection) {
        return self.peripheral.advertisementData.count ;
    }
    return 0 ;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [ToolDetailCell cellHeight];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ToolDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ToolDetailCell class]) forIndexPath:indexPath];
//    cell.accessoryType = indexPath.section ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone ;
    if (indexPath.section) {
        EasyService *tempS = self.peripheral.serviceArray[indexPath.section-1] ;
        EasyCharacteristic *tempC = tempS.characteristicArray[indexPath.row];
        cell.character = tempC ;
        
        NSLog(@"tempc = %@, appdelegete = %@",tempC,[AppDelegate appDelegate].currentCharacteristic);
        switch (_TYPE) {
            case SHOW_TYPE_NOTIY:
            {
                if ([[AppDelegate appDelegate].currentNotiyCharacteristic containsObject:tempC]) {
                    cell.accessoryType = UITableViewCellAccessoryCheckmark;
                }else{
                    cell.accessoryType = UITableViewCellAccessoryNone;
                }
            }
                break;
            case SHOW_TYPE_WRITE:
            {
                if ([[AppDelegate appDelegate].currentCharacteristic isEqual:tempC]) {
                    cell.accessoryType = UITableViewCellAccessoryCheckmark;
                }else{
                    cell.accessoryType = UITableViewCellAccessoryNone;
                }
       
            }
            default:
                break;
        }
        

    }
    else{
        cell.titleString = self.advertisementArray[indexPath.row];
        cell.subTitleString = self.peripheral.advertisementData[self.advertisementArray[indexPath.row]];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section) {
        EasyService *tempS = self.peripheral.serviceArray[indexPath.section-1] ;
        EasyCharacteristic *tempC = tempS.characteristicArray[indexPath.row];
        switch (_TYPE) {
            case SHOW_TYPE_NOTIY:
            {
                NSArray *array  = [tempC.propertiesString componentsSeparatedByString:@" "];
                NSArray *characArray = [NSMutableArray arrayWithArray:array];
                
                if ([characArray containsObject:@"Write"]||[characArray containsObject:@"WriteWithoutResponse"]||[characArray containsObject:@"Read"]) {
                    return;
                }
                
                if (tempC.isNotifying) {
                    if ([AppDelegate appDelegate].currentNotiyCharacteristic.count ==1) {
                        [ALCommon showPromptMessageInPoint:self.view.center text:@"至少要保留一个监听通道" duration:2];
                        return;
                    }
                    [[AppDelegate appDelegate].currentNotiyCharacteristic removeObject:tempC];
                }else{
                    [[AppDelegate appDelegate].currentNotiyCharacteristic addObject:tempC];
                }
                
                [tempC notifyWithValue:!tempC.isNotifying callback:^(EasyCharacteristic *characteristic, NSData *data, NSError *error) {
                    kWeakSelf(self)
                    queueMainStart
                    [weakself.tableView reloadData];
                    queueEnd
                }];

            }
                break;
            case SHOW_TYPE_WRITE:
            {
                NSArray *array  = [tempC.propertiesString componentsSeparatedByString:@" "];
                NSArray *characArray = [NSMutableArray arrayWithArray:array];
                
                if ([characArray containsObject:@"Write"]||[characArray containsObject:@"WriteWithoutResponse"]) {
                    [AppDelegate appDelegate].currentCharacteristic = tempC;
                    [self.tableView reloadData];
                }else if ([characArray containsObject:@"Read"]||[characArray containsObject:@"Notify"]){

                }else if ([characArray containsObject:@"Notify"]||[characArray containsObject:@"Indicate"]){
                }
    
            }
            default:
                break;
        }

    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return [ToolDetailHeaderCell cellHeight] ;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    ToolDetailHeaderCell *headerView = (ToolDetailHeaderCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([ToolDetailHeaderCell class])];
    NSString *serviceName = @"advertisement data" ;
    if (section) {
        EasyService *tempS = self.peripheral.serviceArray[section-1];
        serviceName = tempS.name ;
    }
    headerView.serviceName = serviceName ;
    headerView.sectionState = section==0 ? self.isShowfirstSection : -1 ;
    kWeakSelf(self)
    headerView.callback = ^(BOOL isHidden){
        weakself.isShowfirstSection = isHidden ;
        [weakself.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
    };
    return headerView ;
}

#pragma mark - getter

- (UITableView *)tableView
{
    if (nil == _tableView) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self ;
        _tableView.dataSource = self ;
        _tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ToolDetailCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ToolDetailCell class])];
        [_tableView registerClass:[ToolDetailHeaderCell class] forHeaderFooterViewReuseIdentifier:NSStringFromClass([ToolDetailHeaderCell class])];

        _tableView.tableHeaderView = [ToolDetailHeaderView headerViewWithPeripheral:self.peripheral]; ;
    }
    return _tableView ;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
